package com.le.tester.tip;

/**
 * createTime：2022/2/8 14:42
 * description：long操作的原子性
 */
public class LongAtomTest implements Runnable {

    private static long field = 0;

    private volatile long value;

    public LongAtomTest(long value) {
        this.setValue(value);
    }

    public long getValue() {
        return value;
    }

    public void setValue(long value) {
        this.value = value;
    }

    @Override
    public void run() {
        int i = 0;
        while (i < 10000) {
            //value is volatile
            LongAtomTest.field = this.getValue();
            //field获取值，再进行i++;
            i++;
            long temp = LongAtomTest.field;
            if (temp != 1L && temp != -1L) {
                System.out.println("出现错误结果 " + temp);
                System.exit(0);
            }
        }
        System.out.println(Thread.currentThread().getName() + " running end");
    }

    public static void main(String[] args) throws InterruptedException {
        //获取jvm计算的bit大小
        String arch = System.getProperty("sun.arch.data.model");
        System.out.println(arch + "-bit");
        LongAtomTest t1 = new LongAtomTest(1);
        LongAtomTest t2 = new LongAtomTest(-1);
        Thread thread1 = new Thread(t1);
        Thread thread2 = new Thread(t2);
        thread1.start();
        thread2.start();

        thread1.join();
        thread2.join();

    }
}
